<template>
  <div class="app-container notice">
    <el-row :gutter="10" class="mb6" justify="end">
      <el-col :span="1.5">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="切换检索"
          placement="top-start"
        >
          <el-button
            type="primary"
            plain
            icon="Search"
            circle
            @click="showSearch = !showSearch"
          ></el-button>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="新建公告"
          placement="top-start"
        >
          <el-button
            type="primary"
            icon="Plus"
            @click="handleAdd"
            circle
            v-hasPermi="['system:notice:add']"
        /></el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="编辑公告"
          placement="top-start"
        >
          <el-button
            type="primary"
            plain
            icon="Edit"
            :disabled="single"
            circle
            @click="handleUpdate"
            v-hasPermi="['system:notice:edit']"
        /></el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="下架公告"
          placement="top-start"
        >
          <el-button
            type="primary"
            plain
            icon="CircleClose"
            :disabled="multiple"
            circle
            @click="handleDelete"
            v-hasPermi="['system:notice:remove']"
        /></el-tooltip>
      </el-col>
    </el-row>

    <el-row :gutter="8" justify="space-between">
      <el-col v-show="showSearch" :span="22.5" class="w-full">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item prop="keyword" class="w-3/24">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键词"
              clearable
              class="w-full"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="isRead" class="w-3/24">
            <el-select
              v-model="queryParams.isRead"
              placeholder="公告状态"
              clearable
              class="w-full"
            >
              <el-option
                v-for="dict in is_read"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="announcementType" class="w-3/24">
            <el-tree-select
              class="w-full"
              v-model="queryParams.announcementType"
              placeholder="公告类型"
              check-strictly
              :data="announcementType"
            />
          </el-form-item>
          <el-form-item prop="publishTime" class="w-5/24">
            <el-date-picker
              class="w-full"
              v-model="queryParams.publishTime"
              type="datetimerange"
              range-separator="-"
              start-placeholder="发布开始时间"
              end-placeholder="发布结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item prop="_publishUsers" class="w-3/24">
            <el-select
              class="w-full"
              v-model="queryParams._publishUsers"
              :multiple="true"
              placeholder="发布人员"
              @focus="selectUserFn('publishUsers')"
            >
              <el-option
                v-for="item in userOption['publishUsers']"
                :key="item.uuid"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button
              icon="Refresh"
              @click="groupManage"
              v-hasPermi="['notice:group']"
              >分组管理</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col v-show="!showSearch" :span="22.5" class="mb-6">
        <el-radio-group v-model="queryParams.announcementType">
          <el-radio-button
            v-for="item in latestNotice"
            :key="item.value"
            :label="item.value"
            class="pr-3"
            @change="handleQuery"
            >{{ item.label }}</el-radio-button
          >
        </el-radio-group>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="noticeList"
      @selection-change="handleSelectionChange"
      @row-dblclick="rowClick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="公告标题"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="公告状态" align="center" prop="isRead" width="80">
        <template #default="scope">
          <dict-drop :options="is_read" :value="scope.row.isRead"></dict-drop>
        </template>
      </el-table-column>
      <el-table-column
        label="发布状态"
        align="center"
        prop="isPublish"
        width="160"
      >
        <template #default="scope">
          <div class="flex">
            <dict-drop
              :options="is_publish"
              :value="scope.row.isPublish"
            ></dict-drop>
            <span v-show="scope.row.approvalStatus"
              >({{ scope.row.approvalStatus }})</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="公告类型"
        align="center"
        prop="announcementType"
        width="100"
      >
        <template #default="scope">
          <dict-drop
            :options="announcement_type"
            :value="scope.row.announcementType"
          ></dict-drop>
        </template>
      </el-table-column>
      <el-table-column
        label="发布人员"
        align="center"
        prop="createName"
        width="100"
      />
      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="接收人员"
        align="center"
        prop="receiveType"
        show-overflow-tooltip
        width="180"
      >
        <template #default="scope">
          <div class="inline-block truncate w-full">
            <dict-drop
              :options="receive_type"
              :value="scope.row.receiveType"
              v-if="
                scope.row.receiveType !== '4' && scope.row.receiveType !== '5'
              "
            />
            <span v-else-if="scope.row.receiveType == '4'">{{
              scope.row.receiveUserName
            }}</span>
            <span v-else-if="scope.row.receiveType == '5'">{{
              scope.row.groupName
            }}</span>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:notice:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:notice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />

    <!-- 分组弹出框 -->
    <PersonnelGroup
      v-model:open="groupParams.open"
      :groupConfig="groupParams"
    />
  </div>
</template>

<script setup name="Notice">
import {
  listNotice,
  downNotice,
  noticeUpFiles,
  noticeDelFile
} from '@/api/system/notice'
import { useRouter } from 'vue-router'
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { getTreeNodeByParam, getPricipalId } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const {
  sys_notice_type,
  announcement_type,
  receive_type,
  is_read,
  is_publish
} = proxy.useDict(
  'sys_notice_type',
  'announcement_type', //  --公告类型
  'receive_type', //  --接收类型
  'is_read', // -- 是否已读
  'is_publish' // -- 是否发布
)

// watch(
//   route.query.isRead,
//   val => {
//     if (route.query.isRea) {
//       queryParams.value.isRead = val
//     }
//   },
//   { immediate: true }
// )

const noticeList = ref([])
const loading = ref(true)
const showSearch = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const announcementType = ref(
  computed(() => {
    if (announcement_type.value.length > 0) {
      let types = toRaw(announcement_type.value)
      return proxy.handleTree(types, 'value')
      // console.log('businessTypeOption.value==>', businessTypeOption.value)
    }
  })
)
const latestNotice = ref(
  computed(() => {
    if (announcement_type.value.length > 0) {
      let types = toRaw(announcement_type.value)
      let list = [{ value: '01', label: '全部公告' }]
      return [...list, ...types.filter(e => e.parentId == '01')]
      // console.log('businessTypeOption.value==>', businessTypeOption.value)
    }
  })
)

const data = reactive({
  selectArr: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10
    // announcementType: '01'
  },
  userOption: { publishUsers: [] }, //人员选择下拉
  dialogParam: {}
})

const { selectArr, queryParams, userOption, dialogParam } = toRefs(data)

/** 查询公告列表 */
function getList() {
  // 发布人员
  queryParams.value.publishUsers = getPricipalId(
    userOption.value['publishUsers'],
    queryParams.value._publishUsers
  )
  if (route.query.isRead) {
    queryParams.value.isRead = route.query.isRead
  }
  loading.value = true
  listNotice(queryParams.value).then(response => {
    noticeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  goTo('/rsgl/other/noticeForm')
}
/**修改按钮操作 */
function handleUpdate() {
  goTo('/rsgl/other/editNotice', {
    noticeId: ids.value[0],
    proInsId: selectArr.value[0].proInsId
      ? selectArr.value[0].proInsId
      : undefined
  })
}
/**详情按钮操作 */
function rowClick(row) {
  goTo('/rsgl/other/noticeDetails', { noticeId: row.id })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const noticeIds = row.noticeId || ids.value
  const noticeTitle = row.title || selectArr.value.map(item => item.title)
  proxy.$modal
    .confirm('是否确认下架标题为"' + noticeTitle + '"的公告？')
    .then(function () {
      return downNotice(noticeIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('下架成功')
    })
    .catch(() => {})
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}

/**
 * 人员选择
 * @param keyName handleId:经办人  transactionId:业务员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'publishUsers':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择发布人员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = true
      dialogParam.value.checkStrictly = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [queryParams.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'publishUsers':
      userOption.value.publishUsers = val.selectData
      queryParams.value._publishUsers = val.defaultCheckedKeys
      break
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    queryParams.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      queryParams.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    queryParams.value[fieldName] = obj[0].uuid
  }
}

// 分组参数
const groupParams = ref({
  open: false
})
// 打开分组
const groupManage = () => {
  groupParams.value = {
    open: true,
    options: {
      isEdit: true
    }
  }
}

getList()
</script>
<style lang="scss">
.notice {
  .el-radio-button:first-child .el-radio-button__inner,
  .el-radio-button:last-child .el-radio-button__inner {
    border-radius: initial !important;
  }

  .el-radio-button__inner {
    border: var(--el-border) !important;
  }
  .el-radio-button__original-radio:checked + .el-radio-button__inner {
    box-shadow: none !important;
  }
}
</style>
